package com.njtech.pet.controller;

import com.alibaba.fastjson.JSON;
import com.njtech.pet.entity.Item;
import com.njtech.pet.service.ItemService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：Hana
 * @date ：Created in 2020/3/22 22:36
 * @description：
 * @modified By：
 * @version: $
 */
@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;


    /***********************************************************************用户功能*****************************************************************/


    /**
     * 商品首页
     * @return
     */
    @RequestMapping("/product")
    public String product(){
        return "product";
    }


    /**
     * 用户功能1：查找所有险种
     * @return List<String>
     */
    @RequestMapping("/allItemType")
    @ResponseBody
    public Object allItemType(){
        List type = itemService.selectAllType();
        Map<String,List> map = new HashMap<String,List>();
        map.put("allItemType",type);
        return JSON.toJSONString(map);
    }

    /**
     * 用户功能2：查找所有被保对象
     * @return List<String>
     */
    @RequestMapping("/allItemSubject")
    @ResponseBody
    public Object allItemSubject(){
        List subject = itemService.selectAllSubject();
        Map<String,List> map = new HashMap<String,List>();
        map.put("allItemSubject",subject);
        return JSON.toJSONString(map);
    }

    /**
     * 用户功能3：弹性查询
     * @param req
     * @return List<Item>
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping("/search")
    @ResponseBody
    public Object selectElastically(HttpServletRequest req) throws InvocationTargetException, IllegalAccessException {
        Item item = new Item();
        String type = req.getParameter("type");
        String subject = req.getParameter("subject");
        item.setType(type);
        item.setSubject(subject);
        String upperPrice = req.getParameter("upper");
        String lowerPrice = req.getParameter("lower");
        String[] temp = req.getParameterValues("states");
        Integer upper = null,lower = null;
        List<String> states = null;
        if(type == null || type == ""){
            type = null;
        }
        if(temp != null){
            states = Arrays.asList(temp);
        }
        if(upperPrice != null && upperPrice != ""){
            upper = Integer.parseInt(upperPrice);
        }
        if(lowerPrice != null && lowerPrice != "") {
            lower = Integer.parseInt(lowerPrice);
        }

        List<Item> object = itemService.selectElastically(item,upper,lower,states,req.getParameter("beginDate"),req.getParameter("endDate"),req.getParameter("orderState"));
        Map<String,List> map = new HashMap<String,List>();
        map.put("items",object);
        return JSON.toJSONString(map);
    }


    /**
     * 用户功能4：根据itemId查找商品
     * @param itemId
     * @return
     */
    @RequestMapping("/selectById")
    @ResponseBody
    public Object selectById(Integer itemId){
        Map<String,Object> map = new HashMap<String,Object>();
        Item item = itemService.selectById(itemId);
        map.put("item",item);
        return JSON.toJSONString(map);
    }









    /***********************************************************************管理员功能*****************************************************************/


    /**
     * 管理员功能1：插入商品信息
     * 逐个添加商品，包括商品图片picUrl = itemName_createDate + .jpg
     * @param req
     * @return 受影响的行数
     */

    @RequestMapping("/insert")
    @ResponseBody
    public String insertItem(HttpServletRequest req,MultipartFile file) throws InvocationTargetException, IllegalAccessException, IOException {
        Item item = new Item();
        BeanUtils.populate(item, req.getParameterMap());
        Map<String,String> map = new HashMap<String,String>();

        System.out.print("itemName = " + req.getParameter("itemName") + "\n");

        //设置图片路径
        String itemName = req.getParameter("itemName");
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String webappRoot = classpath.substring(0,classpath.length()-15);
        webappRoot = webappRoot + "src/main/webapp/backstage/images/";
        System.out.print("\n webappRoot：" + webappRoot);

        String originName = file.getOriginalFilename();
        //文件后缀统一转化为小写
        String ext = originName.substring(originName.lastIndexOf(".")).toLowerCase();
        System.out.print("\n ext：" + ext);

        //约束格式
        if(ext.equals(".jpg") || ext.equals(".jpeg") || ext.equals(".png")) {
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
            String now = formatter.format(calendar.getTime());
            System.out.println(now);
            String picUrl = itemName + "_" + now + ext;
            String root = webappRoot + picUrl;
            file.transferTo(new File(root));
            System.out.print("\n picUrl：" + picUrl);
            item.setPicUrl(picUrl);

            //插入一条记录
            Integer num = itemService.insert(item);

            if(num != 0){
                map.put("msg","插入成功");

            }else{
                map.put("msg","插入失败");
            }
        }else{
            map.put("msg","文件格式不正确，仅支持.jpg/.jpeg/.png格式上传");
        }
        return JSON.toJSONString(map);
    }


    /**
     * 管理员功能2：修改商品信息
     * @param req
     * @return 受影响的行数
     */
    @RequestMapping("/update")
    @ResponseBody
    public String updateById(HttpServletRequest req,MultipartFile file) throws InvocationTargetException, IllegalAccessException, IOException {
        Item item = new Item();
        Integer num = 0;
        BeanUtils.populate(item, req.getParameterMap());
        Map<String,String> map = new HashMap<String,String>();
        System.out.print("\nitem :" + item);

        //不修改文件
        if(file == null ){
            //修改一条记录
            num = itemService.updateByItemId(item);
            map.put("msg","修改成功");
        }else{
            //设置图片路径
            String itemName = req.getParameter("itemName");
            String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
            String webappRoot = classpath.substring(0,classpath.length()-15);
            webappRoot = webappRoot + "src/main/webapp/backstage/images/";
            System.out.print("\n webappRoot：" + webappRoot);

            String originName = file.getOriginalFilename();
            //文件后缀统一转化为小写
            String ext = originName.substring(originName.lastIndexOf(".")).toLowerCase();
            System.out.print("\n ext：" + ext);
            //约束格式
            if(ext.equals(".jpg") || ext.equals(".jpeg") || ext.equals(".png")) {
                //获取当前时间
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
                String now = formatter.format(calendar.getTime());
                System.out.println("\n" + now);
                String picUrl = itemName + "_" + now + ext;
                String root = webappRoot + picUrl;
                file.transferTo(new File(root));
                item.setPicUrl(picUrl);
                //修改一条记录
                num = itemService.updateByItemId(item);
                if(num != 0){
                    map.put("msg","修改成功");

                }else{
                    map.put("msg","修改失败");
                }
            }else {
                map.put("msg", "文件格式不正确，仅支持.jpg/.jpeg/.png格式上传");
            }
        }
        if(num == 0){
            map.put("msg","修改失败");
        }
        return JSON.toJSONString(map);
    }
}
